#!/usr/bin/env python
# encoding:utf-8
'''
@author: yangyongjie
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. 
@contact: deamoncao100@gmail.com
software: garner
@file: userapi.py
@time: 2022/8/26 20:29
@desc:
'''
from flask import Blueprint,request
from flask_restful import Resource, Api
from libs.response import generate_response
from model.user import UserManager
from model import db
from forms.user import UserForm, LoginForm
from libs.auth import create_token
from sqlalchemy import or_

user_login_db = Blueprint("userapi", __name__, url_prefix="/v1")
api = Api(user_login_db)

class UserView(Resource):

    def get(self,id=None):
        user_list = []
        keyword = request.args.get("keyword")
        if keyword is not None:
            users_info = UserManager.query.filter(
                or_(UserManager.username.like('%' + keyword + '%'), UserManager.email.like('%' + keyword + '%'))).all()
        else:
            users_info = UserManager.query.all()
        for user in users_info:
            user.film_review = [dict(i) for i in user.reviews]
        user_list += users_info
        return generate_response(message="search user success", data=[user.to_json() for user in user_list])

    def post(self):
        data = request.json
        form = UserForm(data=data)
        if form.validate():
            UserManager.create_user(
                form.username.data,
                # username=data.get("username"),
                password=data.get("password"),
                email=data.get("email"),
                phone_number=data.get("phone_number"),
                role=data.get("role")
            )
            return generate_response(message="add user success")
        else:
            return generate_response(message=form.errors)

    def put(self, id):
        mod_user = UserManager.query.get(id)
        if mod_user:
            # 想要改什么属性，那就接受客户端传递过来的属性即可
            username = request.json.get("username")
            email = request.json.get("email")
            mod_user.username = username
            mod_user.email = email
            db.session.add(mod_user)
            db.session.commit()
            return generate_response(message="modify user success")
        else:
            return generate_response(message="id not found")
    def delete(self, id):
        del_user = UserManager.query.get(id)
        if del_user:
            db.session.delete(del_user)
            db.session.commit()
            return generate_response(message="delete user success")
        else:
            return generate_response(status_code=10001,message="user not found")

#api.add_resource(UserView, "/userapi")
api.add_resource(UserView,"/userapi/<int:id>",endpoint="userview")
#数据验证  wtforms
class LoginView(Resource):
    def post(self):
        data = request.json
        form = LoginForm(data=data)
        user = form.validate()
        if user:
            #验证通过，生成token
            token = create_token(user.id)
            return generate_response(message="login success", data={"token": token})
        else:
            return generate_response(message=form.errors)

api.add_resource(LoginView, "/login")